package com.cennavi.minemapdemo.activity.overlayer;

import android.content.Context;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.activity.BaseActivty;
import com.cennavi.minemapdemo.util.Config;
import com.cennavi.minemapdemo.util.DensityUtil;
import com.cennavi.minemapdemo.util.RandomUtil;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.camera.CameraUpdateFactory;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.geometry.LatLngBounds;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.OverlayFeature;
import com.minedata.minemap.overlay.PolyLineLayer;
import com.minedata.minemap.overlay.PolyLineLayerOptions;
import com.minedata.minemap.overlay.PolyLineLayerOptions.PolylineItem;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lijingru  on 2018/11/5
 */
public class PolyLineLayerActivity extends BaseActivty {

    //地图视图
    private MapView mapView;
    //地图操作类
    private MineMap mineMap;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);
        setContentView(R.layout.activity_polylinelayer);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
        //初始化地图
        initMap();
        initView();
    }
    //生命周期
    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null)
            mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mapView != null)
            mapView.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null)
            mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (mapView != null){
            mapView.onLowMemory();
        }
    }

    public void zoomIn(View view) {
        if (mineMap != null) {
            mineMap.moveCamera(CameraUpdateFactory.zoomIn());
        }
    }

    public void zoomOut(View view) {
        if (mineMap != null) {
            mineMap.moveCamera(CameraUpdateFactory.zoomOut());
        }
    }

    private void initView() {
        findViewById(R.id.zoomin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mineMap != null) {
                    mineMap.animateCamera(CameraUpdateFactory.zoomIn());
                }
            }
        });
        findViewById(R.id.zoomout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mineMap != null) {
                    mineMap.animateCamera(CameraUpdateFactory.zoomOut());
                }
            }
        });
    }

    private void initMap() {

        //mine map sdk 2.0.6之前生效
        // mapView.setStyleUrl(Config.mBaseUrl + Config.MAP_ID);
        mapView.setApiBaseUrl(Config.API_BASE_URL);
        mapView.setApiUrl(Config.API_URL);
        mapView.setSpriteImageUrl(Config.SPRITE_GLYPHS_URL);
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @Override
            public void onMapReady(MineMap oMineMap) {
                mineMap = oMineMap;
                mineMap.getUiSettings().setZoomControlsEnabled(false);
                mineMap.getUiSettings().setRotateGesturesEnabled(false);// 是否可以旋转地图
                mineMap.getUiSettings().setTiltGesturesEnabled(false);
                mineMap.setStyleUrl(Config.BASE_URL + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {

                    @Override
                    public void onStyleLoaded(String s) {

                        //mine map sdk 2.0.6及之后版本这样使用
                        //layers 和 images 都在这里面加载
//                        addLayersToMap();
                    }
                });
                //设置指南针是否显示，默认是显示
                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.getUiSettings().setCompassGravity(Gravity.LEFT);
                mineMap.getUiSettings().setCompassMargins(DensityUtil.dip2px(mContext, 11), DensityUtil.dip2px(mContext, 80),
                        0, 0);
                mineMap.setCameraPosition(
                        new CameraPosition.Builder().target(new LatLng(Config.mapCentrelat,Config.mapCentrelon)).zoom(14)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                mineMap.setMaxZoomPreference(17);//设置最高展示级别，最高为17级别
                mineMap.setMinZoomPreference(3);//设置最低的展示级别
                setOnClick();

            }

        });
    }


    private void setOnClick() {
        if (mineMap != null) {
            mineMap.addOnMapClickListener(new MineMap.OnMapClickListener() {
                @Override
                public void onMapClick(@NonNull LatLng latLng) {
                    getMapEvent(latLng);
                }
            });
        }
    }

    /**
     * 点击事件
     *
     * @param point
     * @return
     */
    private boolean getMapEvent(LatLng point) {
        boolean isHaveEvent = false;
        //捕捉事件
        PointF screenLoc = mineMap.getProjection().toScreenLocation(point);
        float offsize = 5f;
        RectF box = new RectF(screenLoc.x - offsize, screenLoc.y + offsize, screenLoc.x + offsize, screenLoc.y - offsize);
        List<OverlayFeature> featuresEvent = this.mineMap.queryRenderedFeatures(box, "polylineLayer");

        if (featuresEvent.size() > 0) {
            //点击其中一个事件
            for (int i = 0; i < featuresEvent.size(); i++) {
                try {
//                    String evendesc = featuresEvent.get(i).toJson();
                    LatLngBounds latLngBounds = featuresEvent.get(i).bbox();
                    snackbar(this.mapView, latLngBounds.toString());
//                    snackbar(this.mapView, evendesc);
                    isHaveEvent = true;
                    break;
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }

        return isHaveEvent;
    }

    private List<PolylineItem> list;
    private PolyLineLayer polyLineLayer;

    /**
     * 移动
     *
     * @param view
     */
    public void movePolyline(View view) {
        if (list != null && list.size() > 0) {
            List<PolylineItem> listCopy = new ArrayList<>();
            for (PolylineItem item : list) {
                List<LatLng> list = new ArrayList<>();
                for (LatLng latLng : item.getLinePoints()) {
                    list.add(new LatLng((latLng.getLatitude() - 0.001), latLng.getLongitude()));

                }
                listCopy.add(new PolylineItem(list, item.getLineColor()));

            }
            list.clear();
            list.addAll(listCopy);
        }

        if (polyLineLayer != null && polyLineLayer.isLayerExist()) {
            polyLineLayer.clear();
            polyLineLayer.addAll(list);
            polyLineLayer.update();
        }

    }

    /**
     * 动态更改颜色
     *
     * @param view
     */
    public void changeColor(View view) {
        if (list != null && list.size() > 0) {
            List<PolylineItem> listCopy = new ArrayList<>();

            for (PolylineItem item : list) {
                listCopy.add(new PolylineItem(item.getLinePoints(), RandomUtil.randomColor()));
            }
            list.clear();
            list.addAll(listCopy);
        }

        if (polyLineLayer != null && polyLineLayer.isLayerExist()) {
            polyLineLayer.clear();
            polyLineLayer.addAll(list);
            polyLineLayer.update();
        }

    }

    /**
     * 加线段
     *
     * @param view
     */
    public void addPolyline(View view) {
        List<LatLng> lines = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            lines.add(RandomUtil.randomLatLon());
        }
        updata(new PolylineItem(lines, RandomUtil.randomColor()));

    }


    /**
     * 清除
     *
     * @param view
     */
    public void removePolyline(View view) {
        if (polyLineLayer != null && polyLineLayer.isLayerExist()) {
            polyLineLayer.clear();
            polyLineLayer.update();
            list.clear();
        }

    }


    //刷新层
    private void updata(PolylineItem item) {

        if (polyLineLayer == null || !polyLineLayer.isLayerExist()) {
            PolyLineLayerOptions options = new PolyLineLayerOptions("polylineLayer");
            options.add(item);
            options.lineWidth(6);
            options.dashArray(new Float[]{1.5f,1.5f});
            options.lineCapType(PolyLineLayerOptions.LINE_CAP_ROUND);
            options.lineJoinType(PolyLineLayerOptions.LINE_JOIN_ROUND);
            polyLineLayer = mineMap.addLayer(options);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(item);
        } else {
            if (polyLineLayer.isLayerExist()) {

                polyLineLayer.add(item);
                polyLineLayer.update();
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.add(item);
            }
        }
    }

}
